import { Component, OnInit } from '@angular/core';
import {SystemService} from '../system.service';
import {StorageService} from '../../services/storage.service';
import {MenuItem, Message, TreeNode} from 'primeng/primeng';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-person-manage',
  templateUrl: './person-manage.component.html',
  styleUrls: ['./person-manage.component.scss']
})
export class PersonManageComponent implements OnInit {
  orgs: TreeNode[]; //组织树的数据
  selected: TreeNode;                     // 被选中的节点
  selectedNode: TreeNode;                     // 被选中的节点
  selectedCol: any = {};                     // 人员表格中被选中的行
  selectedPid;                     // 人员表格中被选中的行
  selectedNum;                     // 人员表格中被选中的行的人员编号
  state;                      //复用遮罩层的状态,新增还是修改节点
  personState;                      //复用遮罩层的状态,新增还是修改人员
  roleState;                      //复用遮罩层的状态,关联角色还是查看角色
  dataSource;
  tableDatas: any;                   // 人员表格数据
  totalRecords;
  person: FormGroup;
  msgs: Message[]; //提示信息
  items: MenuItem[]; //操作列表,新增，修改，删除
  showOrgEditMask: boolean; //是否显示修改节点弹框
  showOrgDeleteMask: boolean; //是否显示删除节点弹框
  deleteOid; //删除节点的oid
  deleteOrgTip; //删除节点弹框文字
  deletemsgs: Message[]; //删除提示
  canAdd; //新增按钮是否可用
  showPersonEditMask; //是否显示新增人员弹框
  showPerDeleteMask: boolean; //是否显示删除人员弹框
  deletePid; //删除人员的pid
  deletePerTip; //删除人员弹框文字
  selectedPers = []; //选中的人员
  // deletemsgs: Message[];//删除提示
  showCognateRoleMask: boolean; //是否显示关联角色弹框
  showPasswordModMask: boolean; //是否显示修改密码弹框

  constructor(
    private systemService: SystemService,
    private storageService: StorageService,
    private fb: FormBuilder
  ) {
    this.person = fb.group({
        perName: ['', Validators.required],
        pid: ['', Validators.required],
        idcard: ['', Validators.required],
        organization: ['', Validators.required],
        post: [''],
      }
    );
  }

  ngOnInit() {
    //查询组织树
    this.queryOrgTree('');
    //查询人员表格数据
    this.queryPersonList('');
    this.canAdd = true;
    this.showOrgEditMask = false;
    this.showOrgDeleteMask = false;
    this.showPersonEditMask = false;
    this.showCognateRoleMask = false;
    //右击组织节点的弹框列表
    this.items = [
      {label: '新增', icon: 'fa-plus', command: (event) => this.showOrgEdit(this.selected, true)},
      {label: '修改', icon: 'fa-edit', command: (event) => this.showOrgEdit(this.selected, false)},
      {label: '删除', icon: 'fa-close', command: (event) => this.showOrgDelete(this.selected)},
    ];
  }

  //表格数据懒加载
  loadTableData(event){
    setTimeout(() => {
      if (this.dataSource) {
        this.tableDatas = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 250);
  }

  // 弹出新增或者修改节点弹框
  showOrgEdit(node, flag) {
    this.systemService.judgeOrgEditPower().subscribe(res => {// 新增或修改组织节点前，判断当前用户是否有权限
      // console.log(res['errcode']);
      if (res['errcode'] == '00000'){//有权限
        this.showOrgEditMask = true;
        this.selectedNode = node;
        if (flag){//新增
          this.state = 'add';
        }else{//修改
          this.state = 'update';
        }
      }else {//没权限
        this.showError(res);
      }
    });
  }

  //关闭新增或者修改节点弹框
  closeOrgEdit(bool){
    this.showOrgEditMask = bool;
  }

  //新增组织节点成功
  addOrgNode(bool){
    this.showOrgEditMask = bool;
    this.queryOrgTree('');
  }

  //修改组织节点成功
  updateOrgNode(bool){
    this.showOrgEditMask = bool;
    this.queryOrgTree('');
  }

  //显示删除组织节点弹框
  showOrgDelete(node){
    if (node.oid == 1){
      this.showWarn('不可删除根组织！');
    }else {
      this.systemService.judgeOrgEditPower().subscribe(res => {//判断当前用户是否有删除权限
        console.log(res['errcode']);
        if (res['errcode'] == '00000'){//有权限
          this.systemService.getPersonList(node.oid).subscribe(data => {
            if (data.length == 0){
              this.deleteOrgTip = '请确认是否删除组织？';
            }else {
              this.deleteOrgTip = '存在关联人员，删除后组织人员将归并于上一级组织，请确认是否删除？';
            }
            this.showOrgDeleteMask = true;
            this.deleteOid = node.oid;
          }, (err: Error) => {
            console.log(err);
          });
        }else {//没权限
          this.showError(res);
        }
      });
    }
  }

  //删除组织节点
  deleteOrg(){
    this.systemService.deleteOrgNode([this.deleteOid]).subscribe(res => {
      if (res == '00000'){
        this.showSuccess();
        this.showOrgDeleteMask = false;
        this.queryOrgTree('');
      }
    });
  }

  //弹出新增或者修改人员弹框
  showPerEdit(datas) {
    this.systemService.judgePerEditPower().subscribe(res => {
      // console.log(res['errcode']);
      if (res['errcode'] == '00000'){//有权限
        // console.log(this.selected);
        this.showPersonEditMask = true;
        if (!datas){//新增
          // this.selectedCol = this.selected;
          this.selectedCol['label'] = this.selected.label;
          this.selectedCol['oid'] = this.selected['oid'];
          this.selectedCol['birthday'] = '';
          this.personState = 'add';
        }else{//修改
          // this.selectedCol = datas;
          for ( let key in datas ){
            if (datas[key]){
              this.selectedCol[key] = datas[key];
            }else {
              this.selectedCol[key] = '';
            }
          }
          this.selectedCol['label'] = this.selectedCol['organization'];
          this.personState = 'update';
        }
      }else {//没权限
        this.showError(res);
      }
    });
  }

  //显示删除人员弹框
  showPerDelete(datas){
    let deleteFlag = true;
    if (datas){//表格里的删除按钮
      this.selectedPers = [];
      if (datas.oid == 1 && datas.name == '系统管理员'){
        deleteFlag = false;
      }
    }else {//表格外面的删除按钮
      if (!this.selectedPers.length){//没有选中任何人员
        this.showWarn('请先选择删除项！');
      }for (let i = 0; i < this.selectedPers.length; i++){
        if (this.selectedPers[i].oid == 1 && this.selectedPers[i].name == '系统管理员'){
          deleteFlag = false;
          break;
        }
      }
    }
    if (!deleteFlag){
      this.showWarn('不可删除系统管理员！');
    }else{
      this.systemService.judgePerEditPower().subscribe(res => {//判断当前用户是否有删除权限
        if (res['errcode'] == '00000'){//有权限
          this.deletePerTip = '确认删除该人员？';
          this.deletePid = [];
          if (datas){//表格里的删除按钮
            this.showPerDeleteMask = true;
            this.deletePid.push(datas.pid);
          }else {//表格外面的删除按钮
            if (!this.selectedPers.length){//没有选中任何人员
              this.showWarn('请先选择删除项！');
            }else{
              this.showPerDeleteMask = true;
              for (let i = 0; i < this.selectedPers.length; i++){
                this.deletePid.push(this.selectedPers[i].pid);
              }
            }
          }
        }else {//没权限
          this.showError(res);
        }
      });
    }
  }

  //删除人员
  deletePer(){
    this.systemService.deletePerson(this.deletePid).subscribe(res => {
      if (res == '00000'){
        this.selectedPers = [];
        this.showSuccess();
        this.showPerDeleteMask = false;
        this.queryPersonList(this.selected ? this.selected['oid'] : '');
      }
    });
  }

  //关闭新增或者修改人员弹框
  closePersonEdit(bool){
    this.showPersonEditMask = bool;
  }

  //新增人员成功
  addPersonNode(bool){
    this.showPersonEditMask = bool;
    this.queryPersonList(this.selected['oid']);
  }

  //修改人员成功
  updatePersonNode(bool){
    this.showPersonEditMask = bool;
    if (this.selected){//组织树有选中节点
      this.queryPersonList(this.selected['oid']);
    }else{//组织树没有选中节点
      this.queryPersonList('');
    }
  }

  //关联角色和查看角色
  showCogRoleMask(datas, bool){
      console.log(datas);
    if (bool){//关联角色
      this.systemService.judgeRoleEditPower().subscribe(res => {//判断当前用户是否有关联角色权限
        if (res['errcode'] == '00000'){//有权限
          this.showCognateRoleMask = true;
          this.selectedPid = datas;
          this.roleState = 'cognate';
        }else {//没权限
          this.showError(res);
        }
      });
    }else {//查看角色
      this.showCognateRoleMask = true;
      this.selectedPid = datas;
      this.roleState = 'look';
    }
  }

  //关闭关联角色弹框
  closeCognateRole(bool){
    this.showCognateRoleMask = bool;
  }

  //关联角色成功
  cognateRoleBack(bool){
    this.showCognateRoleMask = bool;
    // this.queryOrgTree('');
  }

  //修改密码
  modifyPassword(datas){
    this.systemService.judgePerEditPower().subscribe(res => {
      if (res['errcode'] == '00000'){//有权限
        console.log(datas);
        this.showPasswordModMask = true;
        this.selectedNum = datas.pid;
      }else {//没权限
        this.showError(res);
      }
    });
  }

  //关闭修改密码弹框
  closePasswordMod(bool){
    this.showPasswordModMask = bool;
  }

  //修改密码成功
  passwordModifyBack(bool){
    this.showPasswordModMask = bool;
  }

  // 组织树懒加载
  nodeExpand(event) {
    if (event.node) {
      this.systemService.getOrgTree(event.node.oid).subscribe(data => {
        console.log(data);
        event.node.children = data;
      });
    }
  }

  // 组织树选中
  NodeSelect(event) {
    this.canAdd = false;
    if (parseInt(event.node.dep) >= 1) {
      this.selectedPers = [];
      this.queryPersonList(event.node.oid);
    }
  }

  //查询组织树数据
  queryOrgTree(oid){
    this.systemService.getOrgTree(oid).subscribe(data => {
      console.log(data);
      this.orgs = data;
    });
  }

  //查询人员表格数据
  queryPersonList(oid){
    this.systemService.getPersonList(oid).subscribe(data => {
      // console.log(data);
      this.dataSource = data;
      this.totalRecords = data.length;
      this.tableDatas = this.dataSource.slice(0, 10);
    });
  }

  showWarn(operator: string) {
    this.msgs = [];
    // this.msgs.push({severity:'warn', summary:'注意', detail:'您没有' + operator + '权限！'});
    this.msgs.push({severity: 'warn', summary: '注意', detail: operator });
  }

  //成功提示
  showSuccess() {
    this.deletemsgs = [];
    this.deletemsgs.push({severity: 'success', summary: '消息提示', detail: '删除成功'});
  }

  //错误提示
  showError(res) {
    this.msgs = [];
    this.msgs.push({severity: 'error', summary: '消息提示', detail: res['errmsg']});
  }

}
